package com.ssky.bean.validator;

import com.ssky.bean.validator.core.Feedback;
import com.ssky.bean.validator.core.FieldValidator;
import com.ssky.bean.validator.core.IValidator;
import com.ssky.bean.validator.core.IValidatorContext;
import com.ssky.bean.validator.core.exception.VldException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ssky
 * @Date: 2021/07/30
 * @Description:
 */
public class BeanValidator<B> implements IValidator<Feedback, B> {
    public static final Logger L = LoggerFactory.getLogger(BeanValidator.class);


    private String validatorId;

    private FieldValidator<Feedback, B> fieldValidator;

    private IValidatorContext context;

    private final Class<?> javaBeanClass;

    public BeanValidator(String validatorId) {
        this(validatorId, null, null);
    }

    public BeanValidator(String validatorId, FieldValidator<Feedback, B> fieldValidator, IValidatorContext context) {
        this.validatorId = validatorId;
        this.fieldValidator = fieldValidator;
        this.context = context;
        this.javaBeanClass = fieldValidator.getField().getBeanClassType();
    }

    @Override
    public String getId() {
        return this.validatorId;
    }

    @Override
    public List<Feedback> validate(B javabean) throws VldException {
        if (!this.javaBeanClass.isInstance(javabean)) {
            throw new VldException("validate instance beanClassType:" + javabean.getClass().getName() + "  mismatch of ValidatorId:" + this.validatorId + " validateBeanClass:" + this.javaBeanClass.getName());
        }
        List<Feedback> fbs = new ArrayList<>();
        try {
            fieldValidator.validate(null, javabean, context, fbs);
        } catch (Exception e) {
            L.error("beanValidator validatorId(" + validatorId + ") validate method execute occur excepiton -->", e);
            throw new VldException("beanValidator validatorId(" + validatorId + ") validate method execute occur excepiton -->" + e.getMessage());
        }
        return fbs;
    }

    public String getValidatorId() {
        return validatorId;
    }

    public void setValidatorId(String validatorId) {
        this.validatorId = validatorId;
    }

    public FieldValidator<Feedback, B> getFieldValidator() {
        return fieldValidator;
    }

    public void setFieldValidator(FieldValidator<Feedback, B> fieldValidator) {
        this.fieldValidator = fieldValidator;
    }

    public IValidatorContext getContext() {
        return context;
    }

    public void setContext(IValidatorContext context) {
        this.context = context;
    }
}
